package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String POST_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value(value = "${zzyl.wechat.appid}")
    private String appid;

    @Value(value = "${zzyl.wechat.secret}")
    private String secret;


    /**
     * 获取openId
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = getAppConfig();
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");

        String result = HttpUtil.get(GET_OPEN_ID_URL,paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 判断返回结果的错误代码是否不为null
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            // 抛出异常
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        String openid = jsonObject.getStr("openid");

        return openid;
    }

    /**
     * 通过phoneCode获取手机号
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        // 获取accessToken
        String token = getToken();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code",phoneCode);

        String result = HttpUtil.post(POST_PHONE_URL+token, JSONUtil.toJsonStr(paramMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);


        if (jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
    }

    /**
     * 获取token
     * @return
     */
    private String getToken() {
        Map<String, Object> paramMap = getAppConfig();
        paramMap.put("grant_type","client_credential");

        String result = HttpUtil.get(GET_TOKEN_URL, paramMap);

        JSONObject jsonObject = JSONUtil.parseObj(result);

        String token = jsonObject.getStr("access_token");
        if (StringUtil.isEmpty(token)) {
            throw new RuntimeException("token获取失败");
        }

        return token;
    }

    /**
     * 获取app的id和密钥
     * @return
     */
    private Map<String,Object> getAppConfig() {
        Map<String, Object> appConfig = new HashMap<>();
        appConfig.put("appid",appid);
        appConfig.put("secret",secret);
        return appConfig;
    }
}
